package com.zhonghan.recharge.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.StringUtil;
import com.zhonghan.common.bean.Result;
import com.zhonghan.common.enums.ResultStatus;
import com.zhonghan.common.utils.StringUtils;
import com.zhonghan.common.wechat.api.SnsApi;
import com.zhonghan.common.wechat.bean.sns.SnsToken;
import com.zhonghan.common.wechat.bean.user.SnsUserInfo;
import com.zhonghan.recharge.pojo.ApplyBuyCardOrder;
import com.zhonghan.recharge.pojo.User;
import com.zhonghan.recharge.pojo.ZhBusinessGascardOrder;
import com.zhonghan.recharge.pojo.ZhBusinessUser;
import com.zhonghan.recharge.pojo.ZhFillCard;
import com.zhonghan.recharge.pojo.ZhGascardOrder;
import com.zhonghan.recharge.service.ApplyBuyCardOrderService;
import com.zhonghan.recharge.service.UserService;
import com.zhonghan.recharge.service.ZhBusinessGascardOrderService;
import com.zhonghan.recharge.service.ZhBusinessUserService;
import com.zhonghan.recharge.service.ZhFillCardService;
import com.zhonghan.recharge.service.ZhGascardOrderService;

/**
 * 页面跳转控制层
 * @author zhangceven
 *
 */
@Controller
public class PageController {

	@SuppressWarnings("unused")
	private Logger logger = Logger.getLogger(PageController.class);
	
	@Autowired
	private UserService userService;
	@Autowired
	private ZhGascardOrderService zhGascardOrderService;
	@Autowired
	private ZhFillCardService zhFillCardService;
	@Autowired
	private ZhBusinessUserService zhBusinessUserService;
	@Autowired
	private ZhBusinessGascardOrderService zhBusinessGascardOrderService;
	@Autowired
	private ApplyBuyCardOrderService applyBuyCardOrderService;
	
	@Value("${wechat.APPID}")
	private String APPID;
	@Value("${wechat.APPSECRET}")
	private String APPSECRET;
	@Value("${wechat.DOMAIN}")
	private String DOMAIN;
	
	/**
	 * 跳转页面
	 * @param request
	 * @param response
	 * @param page 如果为空则跳转到首页,不为空则跳转到相应页面
	 * @return
	 */
	@RequestMapping({"/","/index"})
	public String showIndex(HttpServletRequest request, HttpServletResponse response) {
		
		return "index";
	}
	
	/**
	 * 跳转到登录页面
	 * @return
	 */
	@RequestMapping(value="/admin/login", method=RequestMethod.GET)
	public String showLogin(){
		
		return "admin/login";
	}
	
	/**
	 * 登录操作
	 * @param request
	 * @param response
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping(value="/admin/login", method=RequestMethod.POST)
	@ResponseBody
	public Result toLogin(HttpServletRequest request, HttpServletResponse response, String username, String password){
		Result result = new Result();
		
		if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
			result.setCode(ResultStatus.FAILURE.getCode());
			result.setMsg("账号或密码不能为空");
		}else{
			User obj = new User();
			obj.setUsername(username);
			obj.setPassword(StringUtils.md5EncryptWithSalt(password, "zhonghan"));
			try {
				List<User> userList = userService.selectUserByObj(obj );
				
				if(userList != null && userList.size()>0){
					User user = userList.get(0);
					user.setLastLoginTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					String ipAddress = StringUtils.getIpAddress(request);
					user.setLastLoginIp(ipAddress);
					userService.updateNonEmptyUserById(user);
					user.setPassword("");
					
					
					request.getSession().setAttribute("zhonghan_user", user);
					result.setCode(ResultStatus.SUCCESS.getCode());
					result.setMsg("登录成功!");
					result.setData("/admin/index");
				}else{
					result.setCode(ResultStatus.FAILURE.getCode());
					result.setMsg("登录失败,请检查账号或密码是否正确!");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				result.setCode(ResultStatus.BUSYNESS.getCode());
				result.setMsg("登录失败,请检查账号或密码是否正确!");
			}
		}
		return result;
	}
	
	/**
	 * 跳转到后台界面
	 * @return
	 */
	@RequestMapping("/admin/layout")
	public String showLayout(){
		
		return "layout";
	}
	
	/**
	 * 跳转到后台界面2
	 * @return
	 */
	@RequestMapping("/admin/index")
	public String showLayoutII(){
		
		return "admin/index";
	}
	
	/**
	 * 退出登录
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/admin/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response){
		request.getSession().removeAttribute("zhonghan_user");
		
		return "redirect:/admin/login";
	}
	
	/**
	 * 跳转到后台首页
	 * @return
	 */
	@RequestMapping("/admin/homepage")
	public String showHomePage(Model model){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		// 查询今日订单量
		ZhGascardOrder order = new ZhGascardOrder();
		order.setOrderTime(sdf.format(new Date()));
		long orderNum = zhGascardOrderService.getZhGascardOrderRowCountByObj(order );
		model.addAttribute("OrderNum", orderNum);
		
		// 查询充值卡消费量
		ZhFillCard card = new ZhFillCard();
		card.setStatus(2);
		card.setConsumeTime(sdf.format(new Date()));
		long cardNum = zhFillCardService.getZhFillCardRowCountByObj(card );
		model.addAttribute("CardNum", cardNum);
		
		// 查询今日订单撤销量
		ZhGascardOrder revoke = new ZhGascardOrder();
		revoke.setRechargeState("9");
		revoke.setOrderTime(sdf.format(new Date()));
		long revokeOrderNum = zhGascardOrderService.getZhGascardOrderRowCountByObj(revoke );
		model.addAttribute("RevokeOrderNum", revokeOrderNum);
		
		//查询今日的销售总金额
		Integer price =0;
		//拿到今天已消费的对象
		List<ZhFillCard> selectZhFillCardByObj = zhFillCardService.getZhFillCardByObj(card);
		for (ZhFillCard zhFillCard : selectZhFillCardByObj) {
			Integer facePrice = zhFillCard.getFacePrice();
			price +=facePrice;
		}
		model.addAttribute("price", price);
		
		
		return "admin/homepage";
	}

	
	/**
	 * 跳转到商户登录页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/business/login",method=RequestMethod.GET)
	public String showUserLogin(HttpServletRequest request,HttpServletResponse response){
		
		return "business/login";
	}
	
	/**
	 * 商户退出登录
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/business/logout")
	public String userLogout(HttpServletRequest request,HttpServletResponse response){
		
		request.getSession().removeAttribute("zhonghan_business_user");
		
		return "redirect:/business/login";
	}
	
	/**
	 * 用户登录操作
	 * @param request
	 * @param response
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping(value="/business/login", method=RequestMethod.POST)
	@ResponseBody
	public Result toUserLogin(HttpServletRequest request, HttpServletResponse response, String phone, String password){
		Result result = new Result();
		
		if(StringUtil.isEmpty(phone) || StringUtil.isEmpty(password)){
			result.setCode(ResultStatus.FAILURE.getCode());
			result.setMsg("账号或密码不能为空");
		}else{
			ZhBusinessUser obj = new ZhBusinessUser();
			obj.setPhone(phone);
			obj.setPassword(StringUtils.md5EncryptWithSalt(password, "zhonghan"));
			System.out.println(obj.getPassword());
			try {
				List<ZhBusinessUser> userList = zhBusinessUserService.selectZhBusinessUserByObj(obj);
				
				if(userList != null && userList.size()>0){
					ZhBusinessUser user = userList.get(0);
					user.setPassword("");
					request.getSession().setAttribute("zhonghan_business_user", user);
					result.setCode(ResultStatus.SUCCESS.getCode());
					result.setMsg("登录成功!");
					result.setData("/business/index");
				}else{
					result.setCode(ResultStatus.FAILURE.getCode());
					result.setMsg("登录失败,请检查账号或密码是否正确!");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				result.setCode(ResultStatus.BUSYNESS.getCode());
				result.setMsg("登录失败,请检查账号或密码是否正确!");
			}
		}
		
		return result;
	}
	
	/**
	 * 跳转到用户个人中心管理页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/business/index")
	public String showUserIndex(HttpServletRequest request, HttpServletResponse response){
		
		return "business/index";
	}
	/**
	 * 跳转到商户 加油充值
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/business/torecharge")
	public String showBusinessRecharge(HttpServletRequest request, HttpServletResponse response){
		
		return "business/commercialTop";
	}
	
	/**
	 * 跳转到首页
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/business/homepage")
	public String showUserHome(HttpServletRequest request, HttpServletResponse response,Model model){
		ZhBusinessUser user = (ZhBusinessUser) request.getSession().getAttribute("zhonghan_business_user");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// 查询今日订单量
		ZhBusinessGascardOrder order = new ZhBusinessGascardOrder();
		
		order.setOrderTime(sdf.format(new Date()));
		order.setBusinessId(user.getId());
		long orderNum = zhBusinessGascardOrderService.getZhBusinessGascardOrderRowCountByObj(order );
		model.addAttribute("OrderNum", orderNum);
		
		// 查询余额
		user = zhBusinessUserService.selectZhBusinessUserById(user.getId().longValue());
		if(user != null){
			model.addAttribute("TotalAssets", user.getTotalAssets());
		}
		
		//查询今日的销售总金额
		Long saleAmount = zhBusinessGascardOrderService.selectBusinessSaleAmountByObj(order);
		model.addAttribute("SaleAmount", saleAmount);

		return "business/homepage";
	}
	
	/**
	 * 跳转至用户列表
	 * @return
	 */
	@RequestMapping(value="/admin/userList",method=RequestMethod.GET)
	public String showAdmin(){
		
		return "admin/userList";
	}
	
	/**
	 * 获取用户列表
	 */
	@RequestMapping(value="/admin/userList",method=RequestMethod.POST)
	@ResponseBody
	public Result adminList(Integer pageNum,Integer pageSize,String beginTime,String endTime,String username){
		
		Result result = userService.getUserList(pageNum,pageSize,beginTime,endTime,username);
		
		return result;
		
	}
	
	/**
	 * 显示导出卡段页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/admin/showExportCards",method=RequestMethod.GET)
	public String showExportCards(HttpServletRequest request,HttpServletResponse response){
		return "admin/exportCards";
	}
	
	
	/**
	 * 跳转至申请购买油卡页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/applyBuyCard",method=RequestMethod.GET)
	public String showApplyBuyCard(HttpServletRequest request,HttpServletResponse response,Model model){
		
		/*// 接受微信回调回来的code
		String code = request.getParameter("code");
		
		if(StringUtils.isEmpty(code)){
			// 第一步: 生成网页授权url
			String redirect_uri = DOMAIN + "/applyBuyCard";
			String connectOauth2Authorize = SnsApi.connectOauth2Authorize(APPID, redirect_uri, true, "STATE");
			
			try {
				response.sendRedirect(connectOauth2Authorize);
				logger.info("微信网页授权访问申请购买油卡页面");
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			// 第二步: 通过 code 换取网页授权access_token
			String access_token = (String) request.getSession().getAttribute("ACCESS_TOKEN");
			SnsToken snsToken = null;
			
			if(StringUtils.isEmpty(access_token)){
				snsToken = SnsApi.oauth2AccessToken(APPID, APPSECRET, code);
				access_token = snsToken.getAccess_token();
				HttpSession session = request.getSession();
				session.setAttribute("ACCESS_TOKEN", access_token);
				session.setMaxInactiveInterval(7200);
			}
			
			String openid = snsToken.getOpenid();
			
			logger.info("OpenID: " + openid);
			SnsUserInfo snsUserInfo = SnsApi.snsUserinfo(access_token, openid, "zh_CN");
			
			model.addAttribute("SnsUserInfo", snsUserInfo);
			
			return "applyBuyCard";
		}
		
		return null;*/
		
		return "applyBuyCard";
		
	}
	
	/**
	 * 跳转至申请订单页面
	 * @return
	 */
	@RequestMapping(value="/applyBuyCardOrder",method=RequestMethod.GET)
	public String showApplyBuyCardOrder(){
		
		return "admin/applyBuyCardOrder";
	}
	
	
}
